package com.xiaoran.robot.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.jsoup.Jsoup;

import java.io.*;
import java.util.*;

public class StringUtils {
    /**
     * string 转 json
     * @param s
     * @return
     */
    public static JSONObject toJson(String s) {
        return JSON.parseObject(s);
    }


    /**
     * map转 json字符串
     */
    public static String toJson(HashMap<String, Object> map){
        return JSON.toJSONString(map);
    }

    /**
     * 保存文件到本地
     * @param bufferedInputStream
     * @param savePath
     */
    public static void saveFile(BufferedInputStream bufferedInputStream, String savePath) throws IOException {
        //一次最多读取1k
        byte[] buffer = new byte[1024];
        //实际读取的长度
        int readLenghth;
        //根据文件保存地址，创建文件输出流
        FileOutputStream fileOutputStream = new FileOutputStream(new File(savePath));
        //创建的一个写出的缓冲流
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
        //文件逐步写入本地
        while ((readLenghth = bufferedInputStream.read(buffer,0,1024)) != -1){//先读出来，保存在buffer数组中
            System.out.println(readLenghth);
            bufferedOutputStream.write(buffer,0,readLenghth);//再从buffer中取出来保存到本地
        }
        //关闭缓冲流
        bufferedOutputStream.close();
        fileOutputStream.close();
        bufferedInputStream.close();
    }

    /**
     * 根据文本返回对应的回答
     */
    public static String getAnswer(String text){
        String answer = "";
        try {
            String rst = Jsoup.connect("http://api.qingyunke.com/api.php?key=free&appid=0&msg=" + text.trim())
                    .ignoreContentType(true).get()
                    .body().text();
            answer = JSON.parseObject(rst).getString("content").replaceAll("\\{br}", "\n");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return answer;
    }
}
